package services

import (
	"stacks/models"
	"stacks/query"
	"stacks/utils"
)

// UserService 用户服务
type UserService struct{}

// NewUserService 创建用户服务实例
func NewUserService() *UserService {
	return &UserService{}
}

// GetUserByID 根据ID获取用户
func (s *UserService) GetUserByID(id uint) *models.SysUser {
	var user models.SysUser
	err := NewDBWrapper().First(&user, "id = ?", id)
	if err != nil {
		return nil
	}
	return &user
}

// GetUserList 获取用户列表
func (s *UserService) GetUserList(query utils.PageQuery[query.UserQuery]) utils.PageResult {
	var users []models.SysUser
	var total int64

	db := NewDBWrapper()

	// 构建查询条件
	dbInstance := db.GetDB()

	// 添加关键词搜索条件
	if query.Keyword != "" {
		dbInstance = dbInstance.Where("username LIKE ? OR email LIKE ?",
			"%"+query.Keyword+"%", "%"+query.Keyword+"%")
	}

	// 添加状态筛选条件
	if query.Status > 0 {
		dbInstance = dbInstance.Where("status = ?", query.Status)
	}

	// 添加租户筛选条件
	if query.TenantID > 0 {
		dbInstance = dbInstance.Where("tenant_id = ?", query.TenantID)
	}

	// 添加具体查询条件（使用新的泛型结构）
	if query.Conditions.Username != "" {
		dbInstance = dbInstance.Where("username LIKE ?", "%"+query.Conditions.Username+"%")
	}

	if query.Conditions.Email != "" {
		dbInstance = dbInstance.Where("email LIKE ?", "%"+query.Conditions.Email+"%")
	}

	if query.Conditions.Phone != "" {
		dbInstance = dbInstance.Where("phone LIKE ?", "%"+query.Conditions.Phone+"%")
	}

	if query.Conditions.StartTime != "" && query.Conditions.EndTime != "" {
		dbInstance = dbInstance.Where("created_at BETWEEN ? AND ?", query.Conditions.StartTime, query.Conditions.EndTime)
	} else if query.Conditions.StartTime != "" {
		dbInstance = dbInstance.Where("created_at >= ?", query.Conditions.StartTime)
	} else if query.Conditions.EndTime != "" {
		dbInstance = dbInstance.Where("created_at <= ?", query.Conditions.EndTime)
	}

	// 获取总数
	dbInstance.Model(&models.SysUser{}).Count(&total)

	// 分页查询
	offset := (query.Page - 1) * query.PageSize
	dbInstance.Offset(offset).Limit(query.PageSize).Find(&users)

	return utils.PageResult{
		List:  users,
		Total: total,
		Page:  query.Page,
		Size:  query.PageSize,
	}
}

// GetUserListLegacy 兼容旧版本的分页查询
func (s *UserService) GetUserListLegacy(legacyQuery utils.PageQuery[map[string]interface{}]) utils.PageResult {
	// 将旧版本查询转换为新的泛型查询
	var conditions query.UserQuery

	// 直接从查询参数中获取条件
	conditions.Username = legacyQuery.Keyword
	conditions.Email = legacyQuery.Keyword
	conditions.Phone = legacyQuery.Keyword

	// 创建新的查询对象
	newQuery := utils.PageQuery[query.UserQuery]{
		BaseQuery: utils.BaseQuery{
			Page:     legacyQuery.Page,
			PageSize: legacyQuery.PageSize,
			Keyword:  legacyQuery.Keyword,
			Status:   legacyQuery.Status,
			TenantID: legacyQuery.TenantID,
		},
		Conditions: conditions,
	}

	return s.GetUserList(newQuery)
}

// CreateUser 创建用户
func (s *UserService) CreateUser(user *models.SysUser) {
	db := NewDBWrapper()

	// 检查用户名是否已存在
	err := db.CheckUnique(&models.SysUser{}, "username", user.Username)
	if err != nil {
		return
	}

	// 检查邮箱是否已存在
	if user.Email != "" {
		err := db.CheckUnique(&models.SysUser{}, "email", user.Email)
		if err != nil {
			return
		}
	}

	err = db.Create(user)
	if err != nil {
		return
	}
}

// UpdateUser 更新用户
func (s *UserService) UpdateUser(id uint, updates map[string]interface{}) {
	var user models.SysUser
	db := NewDBWrapper()

	// 检查用户是否存在
	err := db.First(&user, "id = ?", id)
	if err != nil {
		return
	}

	// 检查用户名是否重复
	if username, ok := updates["username"].(string); ok {
		err := db.CheckUnique(&models.SysUser{}, "username", username, id)
		if err != nil {
			return
		}
	}

	// 检查邮箱是否重复
	if email, ok := updates["email"].(string); ok {
		db.CheckUnique(&models.SysUser{}, "email", email, id)
	}

	db.Updates(&user, updates)
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(id uint) {
	var user models.SysUser
	db := NewDBWrapper()

	// 检查用户是否存在
	db.First(&user, "id = ?", id)

	db.Delete(&user)
}
